package sc.database.client;

import java.sql.*;

import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;

/**
 * @deprecated
 * 
 * @author Cédric Rais
 *
 */
public class MySQLClient {
	
	private String host;
	private String user;
	private String psw;
	
	private java.sql.Connection dbConnect = null;
	private java.sql.Statement dbStatement = null;
	
	/**
	 * MySQL client constructor
	 * @param host where the database is located (localhost)
	 * @param user username to connect to DB
	 * @param psw password to connect to DB
	 */
	public MySQLClient(String host, String user, String psw){
		this.host = host;
		this.user = user;
		this.psw = psw;
	}
	
	/**
	 * Connect to database
	 * @return true if connection succeed
	 */
	public boolean connectDB(){
		try{
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			dbConnect = DriverManager.getConnection("jdbc:mysql://"+host, user, psw);
			dbStatement = dbConnect.createStatement();
			return true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		
	}

	
    /**
     * Execute insert and update SQL request
     * @param sql resquest as String
     * @return result
     */
    public int execIU(String sql) {
        try {
            int rs = dbStatement.executeUpdate(sql);
            return rs;
        }
        //FIXME catch duplicate entry key exception
        catch(MySQLIntegrityConstraintViolationException ie){
        	System.out.println("Duplicate entry (No Problem)"); //FIXME MARCHE pas c'est tout de SQLException ?!?
        }
        catch (SQLException e) {
        	//e.printStackTrace();
        }
        return 0;
    }
	
    /**
     * Execute select SQL request
     * @param sql resquest as String
     * @return result
     */
    public ResultSet execS(String sql) {
        try {
            ResultSet rs = dbStatement.executeQuery(sql);
            return rs;
        } catch (SQLException e) {
        	e.printStackTrace();
        }
        return null;
    }

    /**
     * Close the connexion
     */
    public void close() {
        try {
            this.dbStatement.close();
            this.dbConnect.close();
            this.dbConnect.close();
        } catch (SQLException e) {
        	e.printStackTrace();
        }
    }
}
